package com.curtis.playwings;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

public class DataDownloadThread extends AsyncTask<Void, Void, JSONArray> {
	public static final int MESSAGE_DOWNLOAD_END = 1;

	private static final String server = "http://curtisoh.com/user/controller/c_flight_data_list_request.php";

	ArrayList<NameValuePair> nameValuePairs;
	String url = server;

	Context context;
	Handler mHandler;
	int page;

	public DataDownloadThread(Context context, Handler mHandler, int page) {
		this.context = context;
		this.mHandler = mHandler;
		this.page = page;
		nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("page", "" + page));
	}

	@Override
	protected JSONArray doInBackground(Void... params) {
		// TODO Auto-generated method stub
		Log.d("ryu", "download start3");
		HttpClient client = new DefaultHttpClient();
		InputStream is = null;
		JSONArray jArray = null;
		try {
			HttpPost httppost = new HttpPost(url);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {	
				sb.append(line + "\n");
			}
			is.close();
			String str=sb.toString();
			jArray = new JSONArray(str);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jArray;
	}
	
	@Override
	protected void onPostExecute(JSONArray jArray) {
		// TODO Auto-generated method stub
		super.onPostExecute(jArray);
		
		if(jArray != null){
			ArrayList<TicketData> dataArray = new ArrayList<TicketData>();
			try {
				for (int i = 0; i < jArray.length(); i++) {
					TicketData data = new TicketData();
					JSONObject json_data = jArray.getJSONObject(i);
					data.number = json_data.getInt("number");
					data.from_city = json_data.getString("from_city");
					data.to_city = json_data.getString("to_city");
					data.from_port = json_data.getString("from_port");
					data.to_port = json_data.getString("to_port");
					data.total_price = json_data.getInt("total_price");
					data.issue_date = json_data.getString("issue_date");
					data.optional_info = json_data.getString("optional_info");
					data.airline = json_data.getString("airline");
					data.update_time = json_data.getString("update_time");
					// data.photo = json_data.getString("photo");
					// data.detail_text =
					// json_data.getString("detail_text");
					try {
						data.from_city = URLDecoder.decode(data.from_city, "utf-8");
						data.to_city = URLDecoder.decode(data.to_city,"utf-8");
						data.from_port = URLDecoder.decode(data.from_port, "utf-8");
						data.to_port = URLDecoder.decode(data.to_port,"utf-8");
						data.optional_info = URLDecoder.decode(data.optional_info, "utf-8");
						data.airline = URLDecoder.decode(data.airline,"utf-8");
						// data.detail_text =
						// URLDecoder.decode(data.detail_text,"utf-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Log.e("ryu","Error utf encoding" + e.toString());
					}
					dataArray.add(data);
				}
			} catch (JSONException e) {
				Log.e("ryu", "Error parsing data " + e.toString());
			}
			mHandler.obtainMessage(MESSAGE_DOWNLOAD_END, dataArray).sendToTarget();
		}
		
	}
}
